package cbfg.http.demo

import android.app.Application
import cbfg.http.HttpManager
import cbfg.http.demo.gank.GankService
import cbfg.http.demo.wanandroid.WanService
import cbfg.http.extra.DefSSLSocketFactory
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import java.util.concurrent.TimeUnit
import javax.net.ssl.HostnameVerifier
import javax.net.ssl.HttpsURLConnection

/**
 * @author:  Tom Hawk
 * 添加时间: 2020/9/10 10:40
 * 功能描述:
 */
class RelApp : Application() {
    override fun onCreate() {
        super.onCreate()

        initHttpManager()
    }

    private fun initHttpManager() {
        val ssl = DefSSLSocketFactory()
        val verifier = HostnameVerifier { hostname, session ->
            HttpsURLConnection.getDefaultHostnameVerifier().verify(hostname, session)
        }

        /*
        //打印信息
        val logger = HttpLoggingInterceptor.Logger { message ->
            Log.d("网络请求", message)
        }
        val loggingInterceptor = HttpLoggingInterceptor(logger)
        loggingInterceptor.level = HttpLoggingInterceptor.Level.BODY
        */

        //有网时候的缓存
        val netCacheInterceptor = Interceptor { chain ->
            val request = chain.request()
            val response = chain.proceed(request)
            val onlineCacheTime = 30 //在线的时候的缓存过期时间，如果想要不缓存，直接时间设置为0
            response.newBuilder()
                .header("Cache-Control", "public, max-age=$onlineCacheTime")
                .removeHeader("Pragma")
                .build()
        }

        /*
        //没有网时候的缓存
        val offlineCacheInterceptor = Interceptor { chain ->
            var request: MethodType = chain.request()
            if (!isNetworkAvailable) {
                val offlineCacheTime = 60 //离线的时候的缓存的过期时间
                request = request.newBuilder()
                    .header(
                        "Cache-Control", "public, only-if-cached, max-stale=" +
                                offlineCacheTime
                    )
                    .build()
            }
            chain.proceed(request)
        }

        //创建缓存
        val httpCacheDirectory = FilePart(mApplicationContext.getCacheDir(), "okhttpCache")
        val cache = Cache(httpCacheDirectory, cacheSize)
        */

        val okHttpClient = OkHttpClient.Builder()
            .connectTimeout(20, TimeUnit.SECONDS)
            .readTimeout(20, TimeUnit.SECONDS)
            //.addNetworkInterceptor(loggingInterceptor)
            .addNetworkInterceptor(netCacheInterceptor)
            //.addInterceptor(offlineCacheInterceptor)
            //.cache(cache)
            .sslSocketFactory(ssl.sslContext.socketFactory, ssl.getTrustManager())
            .hostnameVerifier(verifier)
            .build()

        HttpManager.init(okHttpClient)
            .setLogEnabled(BuildConfig.DEBUG)
            .putHost(GankService.TAG, GankService.URL)
            .putHost(WanService.TAG, WanService.URL)
    }
}